//
//  CommonScanViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/10/19.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "CommonScanViewController.h"

@interface CommonScanViewController ()

@end

@implementation CommonScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [_alphaBtn setBackgroundColor:[Global parseColor:WESTORE_TRANSCLUCENT]];
    [_alphaBtn addTarget:self action:@selector(alphaViewClick) forControlEvents:UIControlEventTouchUpInside];
    // Do any additional setup after loading the view from its nib.
    [self initScan];
}
-(void)alphaViewClick
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;

    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }

}
-(void)initScan
{
    isDown=NO;
    if (_captureSession!=nil) {
        [_captureSession stopRunning];
        [_videoPreviewLayer removeFromSuperlayer];
        _captureSession = nil;
    }
    if (_timer==nil) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
        [self startRead];
    }
    [self.view bringSubviewToFront:_scanBtn
     ];
    [self.view bringSubviewToFront:_lineLabel
     ];
   
}
-(IBAction)scanCancelBtnClick:(id)sender
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;

    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }

}

-(BOOL)startRead
{
    NSError *error;
    
    AVCaptureDevice *captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        // NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    _captureSession = [[AVCaptureSession alloc] init];
    if ([_captureSession canAddInput:input]) {
        [_captureSession addInput:input];
    }
    
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    captureMetadataOutput.rectOfInterest=self.view.frame;
    if ([_captureSession canAddOutput:captureMetadataOutput]) {
        [_captureSession addOutput:captureMetadataOutput];
    }
    
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    captureMetadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code];//@[AVMetadataObjectTypeQRCode];
    
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //  [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    [_videoPreviewLayer setFrame:CGRectMake(0,0,_videoImageView.frame
                                            .size.width,_videoImageView.frame.size.height)];
    //_videoPreviewLayer.connection.videoOrientation = 4;
    [self changePreviewOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
    //  [_bgImageView.layer addSublayer:_videoPreviewLayer];
    // [self.view bringSubviewToFront:_bgImageView];
    [_videoImageView.layer addSublayer:_videoPreviewLayer];
    [_captureSession startRunning];
    return YES;
}
-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    
    [_videoPreviewLayer removeFromSuperlayer];
}
-(void)lineAnimation
{
    if (isDown==NO) {
        num++;
        
        _lineLabel.frame=CGRectMake(_lineLabel.frame.origin.x, 122+2*num,_lineLabel.frame.size.width, _lineLabel.frame.size.height);
        if (2*num>=272) {
            isDown=YES;
            
        }
    }
    else
    {
        num--;
        _lineLabel.frame=CGRectMake(_lineLabel.frame.origin.x, 122+2*num,_lineLabel.frame.size.width, _lineLabel.frame.size.height);
        
        if (num==0) {
            isDown=NO;
        }
    }
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        // if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]&&[metadataObject.stringValue hasPrefix:@"S"]) {
        //  if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]) {
        [self performSelectorOnMainThread:@selector(loadVC) withObject:nil waitUntilDone:NO];
        //}
//        [_captureSession stopRunning];
//       // [_videoPreviewLayer removeFromSuperlayer];
//        _captureSession = nil;
//        [_timer invalidate];
//        _timer=nil;
//      //  [_scanViewContainer removeFromSuperview];
//        if (self.view!=nil) {
//            [self.view removeFromSuperview];
//            [self removeFromParentViewController];
//            
//        }
      //  NSLog(@"stringValue====%@",stringValue);
        
      
    }
    
   
}
-(void)loadVC
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    
    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }

    if ([self.delegate respondsToSelector:@selector(CommonScanResult:)]) {
        [self.delegate CommonScanResult:stringValue];
    }

}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self changePreviewOrientation:(UIInterfaceOrientation)toInterfaceOrientation];
}
- (void)changePreviewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    [CATransaction begin];
    // [CATransaction begin];
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        //  g_orientation = UIImageOrientationUp;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
        
    }else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //  g_orientation = UIImageOrientationDown;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
        
    }else if (interfaceOrientation == UIDeviceOrientationPortrait){
        //  g_orientation = UIImageOrientationRight;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        
    }else if (interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        //  g_orientation = UIImageOrientationLeft;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
    }
    [CATransaction commit];
    
    // [CATransaction commit];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
